package io.renren.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.validator.Assert;
import io.renren.modules.app.dao.ApiUserMapper;
import io.renren.modules.app.entity.UserVo;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.ApiUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *用户服务实现类
 */
@Service("userService")
public class ApiUserServiceImpl extends ServiceImpl<ApiUserMapper, UserVo> implements ApiUserService {

    @Override
    public List<UserVo> queryByMobile(String phone) {
        return this.list(new QueryWrapper<UserVo>().eq("mobile", phone));
    }

    @Override
    public long login(LoginForm form) {
        List<UserVo> users = queryByMobile(form.getMobile());
        Assert.isNull(users, "账户不存在");
        if (users.size() != 1) {
            throw new RRException("账户异常");
        }
        //密码错误
        if (!users.get(0).getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
            throw new RRException("密码有误");
        }
        return users.get(0).getUserId();
    }

}
